#include "usereditor.h"
#include "ui_usereditor.h"
#include "dataview/usermodel.h"
#include "database/dbtabuser.h"

UserEditor::UserEditor(const QModelIndex &index,QWidget *parent) :
    BaseEditor(index,parent),
    ui(new Ui::UserEditor)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint);
    connect(this,SIGNAL(accepted()),this,SLOT(onAccept()));
    this->setGeometry(WINDOW_GEOMETRY_SHIFT(0.4,0.4,0));
    if(!mIsNew)
    {
        ui->leName->setText(index.data(UserModel::ROLE_NAME).toString());
        ui->leID->setText(index.data(UserModel::ROLE_ID).toString());
        ui->cbx_permision->setCurrentIndex(index.data(UserModel::ROLE_PERMISION).toInt());
        ui->lePw->setText(index.data(UserModel::ROLE_PASSWORD).toString());
    }
}

UserEditor::~UserEditor()
{
    delete ui;
}

void UserEditor::onAccept()
{
    emit updateData();
}

void UserEditor::on_btn_cancel_clicked()
{
    this->reject();
}

void UserEditor::on_btn_ok_clicked()
{
    QString name = ui->leName->text();
    if(name.isEmpty())
    {
        MyMessageDialog::warning(0,"错误","请输入用户名");
        return;
    }

    DataBaseQuery query;
    bool accept =false;
    QMap<QString,QVariant> dataMap;
    dataMap.insert(DBTabUser::_USER_NAME,name);
    dataMap.insert(DBTabUser::_USER_CODE,ui->leID->text());
    dataMap.insert(DBTabUser::_PERMISSION,ui->cbx_permision->currentIndex());
    dataMap.insert(DBTabUser::_PASSWD,ui->lePw->text());

    if(DBTabUser::isExist(DBTabUser::TAB_NAME,DBTabUser::_USER_NAME,name))
    {
        QString opt = QString(" \"%1\" = \"%2\"").arg(DBTabUser::_USER_NAME).arg(name);
        accept = query.updateItem(DBTabUser::TAB_NAME,dataMap,opt);
    }
    else
    {
        accept = query.insert(DBTabUser::TAB_NAME,dataMap);
    }
    if(accept)
        this->accept();
    else
        this->reject();
}
